package com.leo.tool.serialize.json;

import com.google.gson.Gson;
import lombok.SneakyThrows;

import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * @author Leo
 * @date 2019/07/08
 */
public class GsonSerializer {

    private static Gson gson = new Gson();

    public static byte[] serialize(Object obj) {
        return gson.toJson(obj).getBytes();
    }

    @SneakyThrows
    public static void serialize(String path, Object obj) {
        Files.write(Paths.get(path), serialize(obj));
    }

    public static <T> T deserialize(byte[] bytes, Class<T> valueType) {
        return gson.fromJson(String.valueOf(bytes), valueType);
    }

    @SneakyThrows
    public static <T> T deserialize(String path, Class<T> valueType) {
        return gson.fromJson(Files.newBufferedReader(Paths.get(path)), valueType);
    }

}
